package tp.pr4.instructions;

import tp.pr4.Message;
import tp.pr4.NavigationModule;
import tp.pr4.RobotEngine;
import tp.pr4.Rotation;
import tp.pr4.instructions.exceptions.InstructionExecutionException;
import tp.pr4.instructions.exceptions.WrongInstructionFormatException;
import tp.pr4.items.ItemContainer;

public class TurnInstruction implements Instruction {

	public TurnInstruction() {
		this.rot = Rotation.UNKNOWN;
	}

	public TurnInstruction(Rotation rotation) {
		this.rot = rotation;
	}

	@Override
	/**
	 * 
	 */
	public Instruction parse(String cad) throws WrongInstructionFormatException {
		String[] words = cad.split(" ");
		if (words.length != 2)
			throw new WrongInstructionFormatException(Message.NOT_UNDERSTAND);
		for (String i : Message.TURN_INSTRUCTION) {
			if (words[0].equalsIgnoreCase(i)
					&& words[1].equalsIgnoreCase("RIGHT"))
				return new TurnInstruction(Rotation.RIGHT);
			else if (words[0].equalsIgnoreCase(i)
					&& words[1].equalsIgnoreCase("LEFT"))
				return new TurnInstruction(Rotation.LEFT);
		}
		throw new WrongInstructionFormatException(Message.NOT_UNDERSTAND);
	}

	@Override
	/**
	 * 
	 */
	public String getHelp() {
		String help = Message.TURN_INSTRUCTION[0];
		for (int i = 1; i < Message.TURN_INSTRUCTION.length; i++)
			help += "|" + Message.TURN_INSTRUCTION[i];
		help += " < LEFT|RIGHT >";
		return help;
	}

	@Override
	/**
	 * 
	 */
	public void configureContext(RobotEngine engine,
			NavigationModule navigation, ItemContainer robotContainer) {
		this.engine = engine;
		this.navigation = navigation;
	}

	@Override
	/**
	 * 
	 */
	public void execute() throws InstructionExecutionException {
		this.navigation.rotate(rot);
		this.engine.addFuel(-5);
		System.out.println(Message.LOOKING.replace("<dir>", this.navigation
				.getCurrentHeading().toString()));

		this.engine.printRobotState();

	}

	private RobotEngine engine;
	private NavigationModule navigation;
	private Rotation rot;
}
